package itbour.onetouchshow.fragment.home;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lsjr.utils.NetUtils;
import com.ys.uilibrary.rv.RecyclerTabLayout;
import com.ys.uilibrary.vp.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.challengezone.video.ChooseVideoSizeActivity;
import itbour.onetouchshow.activity.search.SearchActivity;
import itbour.onetouchshow.base.BaseApplication;
import itbour.onetouchshow.base.mvp.MVPBaseFragment;
import itbour.onetouchshow.bean.HomeDetailslBean;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.fragment.main.MainFragment;
import itbour.onetouchshow.observable.NetWorkObservable;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.sharedpreference.PreferencesHelper;
import itbour.onetouchshow.utils.video.StatusBarUtils;
import itbour.onetouchshow.widget.DesignTableLayout;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 *
 * @author ymz
 *         <p>
 *         首页 玩大片
 */

public class HomeFragment extends MVPBaseFragment<HomeContract.View, HomePresenter> implements HomeContract.View, NetWorkObservable.NetWorkObserver {


    @BindView(R.id.tv_homepage_hotsearch)
    TextView tvHomepageHotsearch;
    @BindView(R.id.rl_circular_shape)
    RelativeLayout rlCircularShape;
    @BindView(R.id.id_vp_home)
    NoScrollViewPager mVpHome;
    @BindView(R.id.id_recyview)
    DesignTableLayout idRecyview;
    List<HomeDetailslBean.TypesBean> mdata = new ArrayList<>();
    //标题
    List<HomeDetailslBean.TypesBean.ChildrenBean> children = new ArrayList<>();
    IndicatorAdapter indicatorAdapter;
    @BindView(R.id.v_status_bar)
    View vStatusBar;
    Unbinder unbinder;
    @BindView(R.id.iv_personal_create)
    ImageView ivPersonalCreate;

    private List<Fragment> fragments = new ArrayList<>();
    private HomePresenter mPresenter = new HomePresenter(this);
    private boolean isfrist = true;

    @Override
    public void loadSucceed(String result) {
        //  SpUtils.getInstance().saveString(AppConst.APPBASEINFO,result);
        showContentView();
//        HomeDetailslBean homeDetailslBean = new Gson().fromJson(result, HomeDetailslBean.class);
//        List<List<Integer>> colorList = homeDetailslBean.getColorList();
//        List<HomeDetailslBean.FontListBean> fontList = homeDetailslBean.getFontList();
//        HomeDetailslBean.TextConfigBean textConfig = homeDetailslBean.getTextConfig();
//        HomeDetailslBean.AppControl appControl = homeDetailslBean.getAppControl();
//        HomeDetailslBean.LengthControl lengthControl = homeDetailslBean.getLengthControl();
//
//        InchingDataSingleCase.INSTANCE.setFontColorList(colorList);
//        InchingDataSingleCase.INSTANCE.setFontTypeList(fontList);
//        InchingDataSingleCase.INSTANCE.setTextConfig(textConfig);
//        InchingDataSingleCase.INSTANCE.setAppControl(appControl);
//        InchingDataSingleCase.INSTANCE.setLengthControl(lengthControl);

        if (!App.initAppInfo) {
            return;
        }
        HomeDetailslBean homeDetailslBean = new Gson().fromJson(SpUtils.getInstance().getString(AppConst.APPBASEINFO), HomeDetailslBean.class);
        List<HomeDetailslBean.TypesBean> types = homeDetailslBean.getTypes();
        if (types == null || types.size() == 0) {
            T_.showToastReal("初始化数据失败");
            loadFaild("");
            return;
        }
        AppConst.mAllType.clear();
        AppConst.mSearchIds.clear();
        for (HomeDetailslBean.TypesBean typesBean : types) {
            //存储所有分类ID
            AppConst.mSearchIds.add(typesBean.getSt_id());
            AppConst.mAllType.put(typesBean.getSt_id(), typesBean.getName());
            //如果等于玩大片取值 否则就设计
            if (typesBean.getName().equals(AppConst.PLAY_LARGE)) {
                mdata.add(typesBean);
            }
        }
        setView();

    }

    @Override
    public void loadFaild(String error) {
        showContentView();
        //  phEmptyDataSet.noData();
        // showErrorView();
        if (!isfrist) {
            //  phEmptyDataSet.hasData();
        }
        isfrist = true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    private void setView() {
        if (mdata == null || mdata.size() == 0) {
            return;
        }
        for (HomeDetailslBean.TypesBean typesBean : mdata) {
            children.clear();
            children.addAll(typesBean.getChildren());
            if (children == null || children.size() == 0) {
                T_.showToastReal("初始化数据失败");
                loadFaild("");
                return;
            }
        }

        /**首页*/
        fragments.clear();
        for (int i = 0; i < children.size(); i++) {
            fragments.add(new MainFragment(i, children.get(i).getSetIds()));
            if (i == 0) {
                /**
                 * 存储所有id
                 */
                SpUtils.getInstance().saveString("AppID", new Gson().toJson(children.get(i).getSetIds()));
            }

        }
        PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager());
        mVpHome.setNoScroll(false);
        mVpHome.setAdapter(pagerAdapter);
        mVpHome.setCurrentItem(0);
        mVpHome.setOffscreenPageLimit(9);
        if (indicatorAdapter == null) {
            indicatorAdapter = new IndicatorAdapter(mVpHome);
        }
        idRecyview.setUpWithAdapter(indicatorAdapter);
        idRecyview.setPositionThreshold(0.5f);
        idRecyview.setIndicatorColor(UIUtils.getColor(R.color.tab_selected));
        idRecyview.setIndicatorHeight(UIUtils.dip2px(2));
        idRecyview.setRecycleViewScollto(true);
        isfrist = false;
        // phEmptyDataSet.hasData();

        HomeDetailslBean homeDetailslBean = new Gson().fromJson(SpUtils.getInstance().getString(AppConst.APPBASEINFO), HomeDetailslBean.class);
        if (homeDetailslBean != null && homeDetailslBean.getAppControl() != null) {
            if (homeDetailslBean.getAppControl().getHiddenCustEntrance() == 1) {
                ivPersonalCreate.setVisibility(View.GONE);
            }
        }
    }

    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }

    @OnClick({R.id.rl_circular_shape, R.id.iv_personal_create})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_circular_shape:
                if (NetUtils.isConnected(getActivity())) {
                    //跳转到搜索界面
                    Intent intent = new Intent(getActivity(), SearchActivity.class);
                    getActivity().startActivity(intent);
                } else {
                    T_.showToastReal("请检查网络");
                }
                break;
            case R.id.iv_personal_create:
                //自由创建入口
                if (PreferencesHelper.getData(AppConst.KEY_PERSONAL_CREATE_CONFIG) == null) {
                    mPresenter.getFreedomCreateConfigInfo();
                } else {
                    openActivity(ChooseVideoSizeActivity.class);
                }
                break;
        }
    }

    @Override
    public void onNetWorkStatusChange(boolean connected) {
        // T_.showToastReal("onNetWorkStatusChange");
        if (connected && isfrist) {
            showLoadingView();
            mPresenter.getHomeDetailsData();
            for (int i = 0; i < fragments.size(); i++) {
                MainFragment fragment = (MainFragment) fragments.get(i);
                fragment.onLoadData();
            }
        }
    }

    @Override
    public void onNewWorkEnvironment(NetWorkObservable.NetStateChangeEvent.NetState netState) {

    }

    private void initStatusBar() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) vStatusBar.getLayoutParams();
        params.height = StatusBarUtils.getStatusBarHeight(getActivity());
        vStatusBar.setLayoutParams(params);
        vStatusBar.setBackgroundColor(getResources().getColor(R.color.app_status_bar_color));
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        //T_.showToastReal("初始化HomeFragment");
        initStatusBar();
        BaseApplication.instance().registerNetWorkObserver(this);
        initData();
        //setView();
//        phEmptyDataSet = new PHEmptyDataSet(mVpHome);
//        phEmptyDataSet.setDelegate(new PHEmptyDataSet.EmptyDataSetDelegate() {
//            @Override
//            public View customView() {
//                View view1 = UIUtils.inflate(R.layout.view_network_error);
//                return view1;
//            }
//        });
        showContentView();
        // phEmptyDataSet.hasData();
    }


    public void initData() {
        // T_.showToastReal("APP 基础信息HomeFragment  iniData===");
        mPresenter.getHomeDetailsData();
    }

    @Override
    public void getConfigSuccess(String configBean) {
        //获取配置信息成功
        PreferencesHelper.saveData(AppConst.KEY_PERSONAL_CREATE_CONFIG, configBean);
    }

    @Override
    public void getConfigFail(String fail) {

    }


    public class IndicatorAdapter extends RecyclerTabLayout.Adapter<IndicatorAdapter.ViewHolder> {
        private PagerAdapter mAdapater;

        public IndicatorAdapter(ViewPager viewPager) {
            super(viewPager);
            mAdapater = (PagerAdapter) mViewPager.getAdapter();
        }


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view;
            if (children.size() < 4) {
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_design_view_tab, parent, false);
            } else {
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_custom_view02_tab, parent, false);
            }

            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {

            holder.text.setText(children.get(position).getName());
            if (children.size() < 4) {
                ViewGroup.LayoutParams layoutParams = holder.ry.getLayoutParams();
                layoutParams.width = UIUtils.WH()[0] / children.size();
            }
            if (position == getCurrentIndicatorPosition()) {
                holder.text.setTextColor(UIUtils.getColor(R.color.tab_selected));
            } else {
                holder.text.setTextColor(0xffffffff);
            }
        }


        @Override
        public int getItemCount() {
            return mAdapater.getCount();
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            TextView text;
            RelativeLayout ry;

            ViewHolder(View itemView) {
                super(itemView);
                text = itemView.findViewById(R.id.text);
                if (children.size() < 4) {
                    ry = itemView.findViewById(R.id.id_ry_root);
                }
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getViewPager().setCurrentItem(getAdapterPosition());
                        //MainFragment mainFragment = (MainFragment) fragments.get(getAdapterPosition());
                        //mainFragment.onLoadData();
                    }
                });
            }
        }
    }

    public class PagerAdapter extends FragmentPagerAdapter {

        PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public String getPageTitle(int position) {
            return children.get(position).getName();
        }


    }
}
